package com.yzion.baselib.utils

import android.graphics.Bitmap
import com.blankj.utilcode.util.CacheMemoryStaticUtils
import com.blankj.utilcode.util.LogUtils

object ImageExt {
    fun Bitmap.hasAlphaChannel(): Boolean {
        val b = CacheMemoryStaticUtils.get<Boolean?>(hashCode().toString())
        LogUtils.i("hasAlphaChannel has cache:$b")
        if (b != null) return b

        val width = width
        val height = height
        val area = width * height

        // 更细粒度的调整策略，根据图片的面积动态调整采样率
        val sampleSize = when {
            area <= 2500 -> 1
            area <= 10000 -> 2
            area <= 40000 -> 3
            area <= 90000 -> 4
            area <= 160000 -> 5
            area <= 250000 -> 6
            area <= 360000 -> 7
            area <= 490000 -> 8
            area <= 640000 -> 9
            area <= 810000 -> 10
            area <= 1000000 -> 12
            area <= 1210000 -> 14
            area <= 1440000 -> 16
            area <= 1690000 -> 18
            area <= 1960000 -> 20
            else -> 25
        }

        when (config) {
            Bitmap.Config.ARGB_8888 -> {
                for (x in 0 until width step sampleSize) {
                    for (y in 0 until height step sampleSize) {
                        if ((getPixel(x, y) shr 24 and 0xff) != 255) {
                            CacheMemoryStaticUtils.put(hashCode().toString(), true)
                            return true
                        }
                    }
                }
            }

            else -> {
                CacheMemoryStaticUtils.put(hashCode().toString(), false)
                return false
            }
        }
        CacheMemoryStaticUtils.put(hashCode().toString(), false)
        return false
    }
}
